<script setup>
import { addArticleCatagoryAPI, updateArticleCatagoryAPI } from '@/api/article'
import { ref, defineEmits } from 'vue'

// emit
const emit = defineEmits(['success'])
// 控制弹出框
const dialogVisible = ref(false)

// 表单数据
const form = ref({})

// 表单对象
const formRef = ref(null)

// 打开弹窗
const open = (value) => {
  dialogVisible.value = true
  if (value) {
    // 更新表单数据为传入的值
    form.value = {
      cate_name: value.cate_name,
      cate_alias: value.cate_alias,
      id: value.id
    }
    title.value = '编辑分类'
  } else {
    form.value = {
      cate_name: '',
      cate_alias: ''
    }
    title.value = '添加分类'
  }
}

// 对外暴露显示切换
defineExpose({
  open
})

// 校验规则
const rules = {
  cate_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名只能包含字母和数字',
      trigger: 'blur'
    }
  ]
}

// 标题
const title = ref('添加分类')

// 上传提交逻辑
const submitForm = () => {
  // 整体校验
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 校验通过，可以提交表单
      // 判断是否是编辑还是新增
      if (title.value === '编辑分类') {
        // 执行编辑逻辑
        // console.log(1)
        const res = await updateArticleCatagoryAPI(form.value)
        // console.log(res)
        ElMessage.success(res.data.message)
      } else {
        // 执行新增逻辑
        console.log(2)
        const res = await addArticleCatagoryAPI(form.value)
        console.log(res)
        ElMessage.success(res.data.message)
      }
      //   通知父组件更新列表
      emit('success')
      // 清除表单内容
      form.value = {}
      // 关闭弹窗
      dialogVisible.value = false
    }
  })
}
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="40%">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="form.cate_name"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="form.cate_alias"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
